package com.TT.utils;

import com.TT.pojo.Content;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

public class HtmlParseUtil {
    public static void main(String[] args) throws IOException {

        new HtmlParseUtil().parseJd("java").forEach(System.out::println);

    }

    public List<Content> parseJd(String keywords) throws IOException {
        //获取请求
        String url = "https://search.jd.com/Search?keyword=" + keywords;

        //解析网页 (Jsoup返回Document就是浏览器Document对象)
        Document document = Jsoup.parse(new URL(url), 30000);

        Element element = document.getElementById("J_goodsList");


        //获取所有li元素
        Elements elements = element.getElementsByTag("li");
        List<Content> goodsList = new ArrayList<Content>();
        //获取元素中的内容,这里el就是每一个li标签
        for (Element el : elements) {
            //关于这种图片特别多的网站，所有的图片都是延迟加载的

            String img = el.getElementsByTag("img").eq(0).attr("source-data-lazy-img");
            String price = el.getElementsByClass("p-price").eq(0).text();
            String title = el.getElementsByClass("p-name").eq(0).text();

            Content content = new Content();
            content.setImg(img);
            content.setPrice(price);
            content.setTitle(title);
            goodsList.add(content);


        }
        return goodsList;
    }

}
